package IO;

import java.io.*;
import java.util.zip.GZIPInputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class TestStream {
    public static void main(String[] args) {
//        testReadFile();
        testReadZip();
    }

    private static void testReadFile() {
        // try-with-resources
        try (InputStream input = new FileInputStream("README.md")) {
            // 读取当前工作目录
            System.out.println("output workspace...");
            System.out.println(System.getProperty("user.dir"));

            for (; ; ) {
                int n = input.read();
                if (n == -1) { // 反复调用read()方法，直到返回-1
                    break;
                }
                System.out.print((char) n);
            }
            System.out.println();
        } // // 编译器在此自动为我们写入finally并调用close()
        catch (FileNotFoundException exception) {
            System.out.println("README.md is not exist.");
        } catch (IOException ignored) {
            System.out.println("OP README.md error.");
        } //
    }

    private static void testReadZip() {
//        File zipFile = new File("readme.zip");
        try (InputStream file = new FileInputStream("readme.zip")) {
            try (ZipInputStream zis = new ZipInputStream(file)) {
                ZipEntry zipEntry = zis.getNextEntry();
                while (zipEntry != null) {
                    File newFile = new File(zipEntry.getName());
//                    newFile.createNewFile();
                    System.out.println("FileName: " + zipEntry.getName());
                    System.out.println(readAsString(zis));

                    zipEntry = zis.getNextEntry();
                }

            } catch (IOException ignored) {
                System.out.println("read readme.zip error.");
            }
        } catch (IOException ignored) {
            System.out.println("readme.zip is not exist.");
        }

    }

    private static String readAsString(ZipInputStream input) throws IOException {
        StringBuilder stringBuilder = new StringBuilder();
        // 定义1000个字节大小的缓冲区:
        byte[] buffer = new byte[1000];

        int n;
        try {
            while ((n = input.read(buffer)) != -1) {
                for (byte b : buffer) {
                    if (b != 0) {
                        stringBuilder.append((char) b);
                    } else {
                        break;
                    }
                }
            }
        } catch (IOException e) {
            System.out.println("op readme.zip byte error.");
        }


        return stringBuilder.toString();
    }
}
